#!usr/bin/env python
#-*- coding:utf-8 -*-
"""
数据源：巨潮 -> 市场资讯 -> 上市公司 -> 公司资讯 -> 分红配股
爬取类目：分红(不包含配股)
股票类型不包括港股（港股没有最新资料）
url_sample: http://www.cninfo.com.cn/information/dividend/szmb000001.html
"""
"""
result_sample_of_company_dividend = {
    '_id': '',
    'stockCode': '',
    'companyShortName': '',
    'stockType': '',
    'dividend': [{
        'dividendYear': '',
        'dividendPlan': '',
        'recordDate': '',
        'rightOutDate': '',
        'bonusOfferDate': '',
    },],
}
"""

import sys

from company_formaltable_crawler import CompanyFormalTable
from company_crawler import CompanyInfoUtil
from xtls.logger import get_logger
from xtls.timeparser import now

reload(sys)
sys.setdefaultencoding('utf-8')

CATEGORY = 'dividend'

DETAIL_MAPPING = {
    u'分红年度': 'dividendYear',
    u'分红方案': 'dividendPlan',
    u'股权登记日': 'recordDate',
    u'除权基准日'	: 'rightOutDate',
    u'红股上市日': 'bonusOfferDate',
}

class CompanyDivided(CompanyFormalTable):
    def __init__(self, company_info_util_instance):
        super(CompanyDivided, self).__init__(company_info_util_instance=company_info_util_instance)

    def save(self, data):
        data['updateTime'] = now()
        for key, value in data.items():
            if key in ['dividendDetail']:
                for dividend_list in value:
                    for child_key, child_value in dividend_list.items():
                        print '{}: {}'.format(child_key, child_value)
                print '-'*40
            else:
                print '{}: {}'.format(key, value)

        print "=" * 70


def main():
    global CATEGORY
    global DETAIL_MAPPING
    from_company_info = CompanyInfoUtil(category=CATEGORY,
                                        detail_mapping=DETAIL_MAPPING)
    from_company_info.set_logger(get_logger(__file__))

    try:
        CompanyDivided(from_company_info).run()
    except:
        from_company_info.logger.warn('%s shuttdown' % from_company_info.category)

if __name__ == '__main__':
    main()

